package com.miao.teacher.ui;

import org.json.JSONException;
import org.json.JSONObject;

import com.espeaker.sdk.Constants;
import com.espeaker.sdk.api.ReviseApi;
import com.espeaker.sdk.utils.JsonUtils;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.miao.teacher.adapter.OrderAdapter;
import com.miao.teacher.app.TApp;
import com.miao.teacher.controls.LocalRevise;
import com.miao.teacher.models.PullOrder;
import com.miao.teacher.models.ReviseInfo;
import com.espeaker.sdk.model.ReviseJson;
import com.miao.teacher.presenters.OnOrderChange;
import com.miao.teacher.utils.DBUtil;
import com.miao.teacher.utils.FileUtil;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class PullFragment extends BaseFragment {

	private ReviseApi api = new ReviseApi();
	private PullToRefreshListView lv = null;

	private OrderAdapter mAdapter = null;

	private AlertDialog alertDialog = null;

	private ProgressDialog pd;

	public OnOrderChange mListener = null;

	private PullOrder mCurOrder = null;

	public static PullFragment newInstance(OnOrderChange listner) {
		PullFragment fragment = new PullFragment();
		fragment.mListener = listner;
		return fragment;
	}

	@Override
	protected void RecMsgFromHandler(Message msg) {
		// TODO Auto-generated method stub
		super.RecMsgFromHandler(msg);
		switch (msg.what) {
		case Constants.REVISE_PULL:
			showOrder(msg.obj);
			break;
		case Constants.REVISE_GRAB:
			grabResult(msg.obj);
			break;
		}
	}

	private void showOrder(Object obj) {
		try {
			final JSONObject json = new JSONObject(obj.toString());
			int status = JsonUtils.getInt(json, "status", -1);
			if (status == 0) {
				JSONObject valueJson = JsonUtils.getJSONObject(json, "values",
						null);
				PullOrder[] orders = doLoadFromNet(valueJson.toString());
				mAdapter = new OrderAdapter(getActivity().getBaseContext(),
						orders);
				try{
				lv.setAdapter(mAdapter);
				
				}catch(Exception er)
				{}
				
				setListener();
			}
			lv.onRefreshComplete();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void grabResult(Object obj) {
		try {
			final JSONObject json = new JSONObject(obj.toString());
			int status = JsonUtils.getInt(json, "status", -1);
			if (status == 0) {
				/*
				 * api.pull(mHandler); if(mListener!=null) {
				 * mListener.onOrderStatusChange(); }
				 */
				if (mCurOrder != null) {
					ReviseInfo mInfo = new ReviseInfo();
					mInfo.xiaofei_id = mCurOrder.id;
					ReviseJson mJson = new ReviseJson();
					mJson.audio_length = mCurOrder.audio_length;
					mJson.audio_url = mCurOrder.audio_url;
					mJson.title = mCurOrder.title;
					mJson.xiaofei_id = mCurOrder.id;
					mJson.created_at=mCurOrder.created_at;
					String userId = FileUtil.getPreferences(getActivity(),
							TApp.USER_ID);
					mJson.revise_id = Integer.parseInt(userId);
					Gson gson = new Gson();
					mInfo.json = gson.toJson(mJson);
					LocalRevise.doAddRevise(new DBUtil(getActivity()).sld,
							mInfo);

					ReviseActivity.createInstance(getActivity(), mCurOrder.id);
				}
			} else {
				ToastShowMsg(R.string.str_pull_grab_fail);
			}
			pd.dismiss();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void setListener() {
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				mCurOrder = (PullOrder) arg0.getItemAtPosition(arg2);
				grapOrder(mCurOrder);
			}
		});
	}

	private void grapOrder(final PullOrder order) {
		alertDialog = new AlertDialog.Builder(getActivity(),
				R.style.AlertDialog).create();
		alertDialog.show();
		final Window window = alertDialog.getWindow();
		window.setContentView(R.layout.dialog_confirm);
		LayoutParams lp = window.getAttributes();
		lp.width = getXPx() - 20;
		window.setAttributes(lp);
		window.findViewById(R.id.img_close).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						alertDialog.dismiss();
					}
				});
		window.findViewById(R.id.btnCancel).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						alertDialog.dismiss();
					}
				});

		window.findViewById(R.id.btnOk).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						String userId = FileUtil.getPreferences(getActivity(),
								TApp.USER_ID);
						api.grab(userId, order.id + "", mHandler);
						pd = ProgressDialog.show(getActivity(), "Doing",
								"Waiting……");
						pd.show();
						alertDialog.dismiss();
					}
				});
	}

	public PullOrder[] doLoadFromNet(String valueJson) {
		PullOrder[] jsonBean = null;
		try {
			valueJson = valueJson.replace("{\"xiaofeis\":", "");
			valueJson = valueJson.substring(0, valueJson.length() - 1);
			Gson gson = new Gson();
			jsonBean = gson.fromJson(valueJson, PullOrder[].class);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonBean;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.layout_revise, null);
		lv = (PullToRefreshListView) view.findViewById(R.id.lvPull);
		lv.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				// TODO Auto-generated method stub
				api.pull(mHandler);
			}
		});
		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		api.pull(mHandler);
	}

}
